<?php

require_once(LIB . "/database/DBEnvironments.php");

/**
 * Database
 * @author joo8111
 */
class Database {

	var $link ;
	var $res ;
	var $obj ;
	var $numRows ;
	var $insertId ;

	function Database($connection_name = "test")
	{
		$this->link = 0;
		$this->obj = null;
		$this->numRows = 0;

		if(!$this->connect($connection_name)) {
			echo"DB connection fail.";
			exit(301);
		}
	}

	function catchError()
	{
		$this->err->setErrMsg ("DB error (" . mysql_errno($this->link) . ") : " . mysql_error($this->link)) ;
		$this->err->setErrMode (ERR_EXIT) ;
		$this->err->printError () ;
	}


	/**
	 * connection_name에 따른 DB연결
	 * @param $connection_name
	 * @return true / false
	 */
	function connect($connection_name)
	{
		$env = new DBEnvironments($connection_name);
		$this->link = mysql_connect($env->hostname, $env->user, $env->password) ;

		if (!$this->link) {
			return false;
		}
		if (!mysql_select_db($env->db, $this->link)) {
			return false;
		}
		
		return true;
	}

	/**
	 * SQL Query를 Database Server에 넘긴다.
	 * @return (성공 : true / 실패 : false)
	 */
	function query ($query)
	{
		$real_query = mysql_real_escape_string($query, $this->link) ;
		$this->res = mysql_query ($query, $this->link) ;
		if (!$this->res) {
			$this->catchError () ;
			$this->printError () ;
			return (false) ;
		}

		if (strpos ($query, "SELECT", 0) === false) {
			$this->numRows = mysql_affected_rows ($this->link) ;
		}
		else {
			if (strpos ($query, "INSERT", 0) === false) {
				$this->insertId = mysql_insert_id($this->link) ;
			}
			$this->numRows = mysql_num_rows ($this->res) ;
		}
		return ($this->res != false) ;
	}

	/**
	 * 하나의 결과 행을 가져온다.
	 * @return (성공 : true / 실패 : false)
	 */
	function fetch ()
	{
		$this->obj = mysql_fetch_object ($this->res) ;
		if (!$this->obj) {
			return (false) ;
		}
		return (true) ;
	}

	/**
	 * 결과를 해제한다.
	 */
	function freeResult ()
	{
		mysql_free_Result ($this->res) ;
		$this->res = 0 ;
		$this->obj = null ;
		return ;
	}

	/**
	 * Result table의 [n, n] 값을 가져온다.
	 *
	 * @param int $row 결과의 row 값
	 * @param int $col 결과의 col 값
	 * @return $val 결과값
	 */
	function result ($row, $col)
	{
		$val = mysql_result($this->res, $row, $col) ;
		return ($val) ;
	}

}
?>